import {Alert, Pressable, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Button, Search, Text, useAppTheme} from 'tsun-smart-ui';
import {deviceApi, AppEquipmentDTO} from '@/services/api/deviceApi';
import {ActionDispatch, useEffect, useRef, useState} from 'react';
import {DeviceStatus} from '@/enums/devices';
import DeviceCard from '@/components/DeviceInfo/DeviceCard';
import {navigationRef} from '@/navigation';
import Swipeable from 'react-native-gesture-handler/ReanimatedSwipeable';
import PageContent, {PageTemplate} from '@/components/PageContent';
import toast from '@/utils/toast';
import {useMMKVObject} from '@/hooks/useMMkv';
import {UserInfo} from '@/services/api/userApi';
import {useSelector} from 'react-redux';
import {RootState} from '@/store';
import {StationDTO} from '@/services/api/stationApi';
import {useIsFocused} from '@react-navigation/native';
export const DeviceItem = ({item}: {item: AppEquipmentDTO}) => {
  return (
    <DeviceCard
      item={item}
      onPress={() => {
        navigationRef.navigate('DeviceInfo', item);
      }}></DeviceCard>
  );
};
export const TotalMap = {
  normal: 'readyCount',
  alarm: 'alarmCount',
  offline: 'offlineCount',
} as const;
const DeviceManage = () => {
  const {t} = useTranslation();
  const [activeTab, setActiveTab] = useState<
    keyof typeof DeviceStatus | undefined
  >();
  const [searchText, setSearchText] = useState('');
  const init = useRef(false);
  const theme = useAppTheme();
  const isFocused = useIsFocused();
  const dispatchPage = useRef<ActionDispatch<[action: any]> | null>(null);
  const [userInfo] = useMMKVObject<UserInfo>('user_info');
  const currentStation = useSelector<RootState, StationDTO | null>(
    state => state.fullScene.currentStation,
  );
  useEffect(() => {
    if (init.current && isFocused) {
      setActiveTab(undefined);
      setSearchText('');
      dispatchPage.current?.({
        type: 'setPageNum',
        payload: 1,
      });
    } else {
      init.current = true;
    }
  }, [currentStation?.id, isFocused]);
  const filterTabs = [
    {
      id: void 0,
      title: t('monitor.chat.options.all'),
    },
    {
      id: 'normal',
      title: t('job.status.Normal'),
    },
    {
      id: 'alarm',
      title: t('user.alarm'),
    },
    {
      id: 'offline',
      title: t('monitor.tab.title.offline'),
    },
  ] as const;
  // 处理删除设备
  const handleDeleteDevice = (device: AppEquipmentDTO) => {
    Alert.alert(
      t('common.confirmButtonText', {defaultValue: '确认'}),
      t('device.deleteConfirm', {defaultValue: '确定要删除该设备吗？'}),
      [
        {
          text: t('user.logOutCancel', {defaultValue: '取消'}),
          style: 'cancel',
        },
        {
          text: t('pb.delete', {defaultValue: '删除'}),
          style: 'destructive',
          onPress: () => {
            // 这里应该调用删除设备的API
            deviceApi.unbindDevice(device.id!).then(async ({data}) => {
              if (data) {
                dispatchPage.current?.({
                  type: 'setPageNum',
                  payload: 1,
                });
              }
              toast[data ? 'success' : 'error']({
                message: t(
                  data ? 'common.delSuccessText' : 'common.actionFailed',
                ),
              });
            });
          },
        },
      ],
    );
  };
  const renderDeviceItem = ({item}: {item: AppEquipmentDTO}) => {
    let isSwipingRef = false;
    // 渲染右侧滑动操作
    const renderRightActions = () => {
      return (
        <Pressable
          className=" justify-center  rounded-xl overflow-hidden"
          onPress={() => {
            handleDeleteDevice(item);
          }}>
          <View
            className="h-full w-[60] flex-center"
            style={{backgroundColor: theme.colors?.error?.primary}}>
            <Text style={{color: theme.colors?.neutral?.white}}>
              {t('pb.delete', {defaultValue: '删除'})}
            </Text>
          </View>
        </Pressable>
      );
    };

    const handleItemPress = () => {
      // 只有在没有滑动的情况下才触发点击
      if (!isSwipingRef) {
        navigationRef.navigate('DeviceInfo', item);
      }
    };

    return (
      <Swipeable
        renderRightActions={renderRightActions}
        rightThreshold={40}
        onSwipeableWillOpen={() => {
          isSwipingRef = true;
        }}
        onSwipeableClose={() => {
          // 延迟重置状态，确保点击事件不会被误触
          setTimeout(() => {
            isSwipingRef = false;
          }, 100);
        }}
        onSwipeableOpen={() => {
          isSwipingRef = true;
        }}>
        <DeviceCard item={item} onPress={handleItemPress}></DeviceCard>
      </Swipeable>
    );
  };
  return (
    <View className="px-4 flex-1 ">
      <PageContent
        renderItem={renderDeviceItem}
        api={deviceApi.getStationEquipment}
        params={{
          deviceStatus: activeTab,
          deviceName: searchText,
          deviceSn: searchText,
          stationId: userInfo?.userType === 1 ? currentStation?.id : void 0,
        }}>
        <PageTemplate.default>
          {({dispatch, setTotal, setHasMore, restData}) => {
            dispatchPage.current = dispatch;
            return (
              <>
                <Search
                  className="mt-[10px]"
                  placeholder={t('common.search')}
                  value={searchText}
                  onChangeText={setSearchText}
                  cancelText={t('user.logOutCancel', {defaultValue: '取消'})}
                  onSubmitEditing={() => {
                    dispatch({
                      type: 'setPageNum',
                      payload: 1,
                    });
                  }}></Search>
                <View className="flex-row my-1 justify-between">
                  {filterTabs.map((tab, i) => (
                    <View key={i} className="">
                      <Button
                        size="large"
                        variant="text"
                        title={`${tab.title}${`(${
                          restData?.statusCount?.[
                            TotalMap[tab.id!] ?? 'total'
                          ] ?? '0'
                        })`}`}
                        textStyle={{
                          color:
                            activeTab === tab.id
                              ? theme.colors?.brand?.primary
                              : theme.colors?.neutral?.secondaryTitle,
                        }}
                        onPress={() => {
                          setTotal(undefined);
                          dispatch({
                            type: 'setPageNum',
                            payload: 1,
                          });
                          setHasMore(true);
                          setActiveTab(tab.id);
                        }}></Button>
                    </View>
                  ))}
                </View>
              </>
            );
          }}
        </PageTemplate.default>
      </PageContent>
    </View>
  );
};
export default DeviceManage;
